package com.cskaoyan.config;

import com.cskaoyan.realm.CustomRealm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

@Configuration
public class ShiroConfiguration {

    @Bean
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);
        //认证失败访问的url默认是login.jsp 👉 这个不再使用，认证失败，响应的是Json，我们后端不做重定向
        //factoryBean.setLoginUrl();

        //配置请求url和认证和权限之间的关系 👉 url 👉 shiro的filter
        /**
         * key和value的类型都是字符串
         *          key：请求url
         *          value：filter
         * LinkedHashMap  👉 有序
         */
        LinkedHashMap<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/hello", "anon");
        filterMap.put("/admin/auth/login", "anon");      //通常登录请求设置为匿名请求
        filterMap.put("/admin/auth/info", "anon");
        //filterMap.put("/user/list", "authc"); //这个请求url需要在认证成功之后才能访问
        //通常很多请求都需要在认证之后才能方法，使用通配符
        filterMap.put("/**", "authc");        //访问请求，先要执行authc的filter，判断是否是认证状态
        factoryBean.setFilterChainDefinitionMap(filterMap);
        return factoryBean;
    }

    @Bean
    public DefaultWebSecurityManager securityManager(CustomRealm realm,
                                                     CskaoyanSessionManager sessionManager) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //给默认的认证器和授权器提供realm
        securityManager.setRealm(realm);
        securityManager.setSessionManager(sessionManager);
        return securityManager;
    }

    //整合商城应用，跨域了，session变化了
    //sessionManager
    @Bean
    public CskaoyanSessionManager sessionManager() {
        CskaoyanSessionManager cskaoyanSessionManager = new CskaoyanSessionManager();
        cskaoyanSessionManager.setGlobalSessionTimeout(600000);
        cskaoyanSessionManager.setDeleteInvalidSessions(true);
        return cskaoyanSessionManager;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}
